
const co = require('co');
const http = require('./builder.httpRequest');
const path = require('path');
const shell = require('./builder.shell');

const BuildHelper = function () {
    let _downloadImage = function *(distPath,imgURL) {
        let fileName = path.basename(imgURL);
        console.log(`download: ${fileName} <= ${imgURL}`);
        let result = yield shell.exec(`curl ${imgURL}  -o ${distPath}/assets/${fileName}`);
        return result !== false ? `/assets/${fileName}` : false;
    }
    let _getAppConfig = function *(appName) {
        let opt = {
            host: "localhost",
            port: 9021,
            path: `/tools/app/getConfig?appName=${appName}`,
            method: "GET"
        };
        console.log(opt);
        const ret = yield http.request(opt, true);
        try{
            if (ret.apiStatus && ret.apiStatus.statusCode == 0 && ret.result){
                return ret.result;
            }else{
                return null;
            }
        }catch(e){
            console.log(e);
            return null;
        }
    }

    let _getAppPages = function *(appId) {
        let opt = {
            host: "localhost",
            port: 9021,
            path: `/tools/app/getPages?appId=${appId}`,
            method: "GET"
        };
        const ret = yield http.request(opt, true);
        try{
            if (ret.apiStatus && ret.apiStatus.statusCode == 0 && ret.result){
                return ret.result;
            }else{
                return null;
            }
        }catch(e){
            console.log(e);
            return null;
        }
    }


    return {
        getAppConfig: _getAppConfig,
        getAppPages: _getAppPages,
        downloadImage: _downloadImage
    }
}();


module.exports = BuildHelper;
